﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.ApplicationServer.Caching;


namespace VelocityDemo.Web.FeatureDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnPut_Click(object sender, EventArgs e)
        {

            DataCacheServerEndpoint[] cluster = GetClusterEndpoints();

            DataCacheFactoryConfiguration cfg = new DataCacheFactoryConfiguration();
            cfg.Servers = cluster;
            cfg.LocalCacheProperties = new DataCacheLocalCacheProperties();
            cfg.SecurityProperties = new DataCacheSecurity(DataCacheSecurityMode.None,
                                                           DataCacheProtectionLevel.None);

            DataCacheFactory factory = new DataCacheFactory(cfg);
            DataCache cache = factory.GetCache("DemoCache");

            cache.Put("Value1", TextBox1.Text);
            TextBox1.Text = "";
        }

        protected void btnGet_Click(object sender, EventArgs e)
        {
            lblResult.Text = "";

            DataCacheServerEndpoint[] cluster = GetClusterEndpoints();

            DataCacheFactoryConfiguration cfg = new DataCacheFactoryConfiguration();
            cfg.Servers = cluster;
            cfg.LocalCacheProperties = new DataCacheLocalCacheProperties();
            cfg.SecurityProperties = new DataCacheSecurity(DataCacheSecurityMode.None,
                                                           DataCacheProtectionLevel.None);

            DataCacheFactory factory = new DataCacheFactory(cfg);
            DataCache cache = factory.GetCache("DemoCache");

            string result = (string)cache.Get("Value1");

            if (result == null)
                lblResult.Text = "(null)";
            else
                lblResult.Text = result;
        }

        public DataCacheServerEndpoint[] GetClusterEndpoints()
        {
            DataCacheServerEndpoint[] cacheCluster;

            if (optUseSingleServerCluster.Checked)
            {
                cacheCluster = new DataCacheServerEndpoint[1];
                cacheCluster[0] = new DataCacheServerEndpoint("localhost", 22233);
            }
            else
            {
                cacheCluster = new DataCacheServerEndpoint[3];
                cacheCluster[0] = new DataCacheServerEndpoint("server1", 22233);
                cacheCluster[1] = new DataCacheServerEndpoint("server2", 22233);
                cacheCluster[2] = new DataCacheServerEndpoint("server3", 22233);

            }
            
            return cacheCluster;
        }

    }
}
